<?php
/*MySQL Connection*/
include("DatabaseConnectionInformation.php");
/*Cookie time to live (in days)*/
$cookieTTL = 3;
//setcookie("last_login","");
session_start();

?>
<?php
$successfulLogin = false;
if ( (isset($_POST["login"])) && ( isset($_POST["pass"])) && (!empty($_POST["login"])) && (!empty($_POST["pass"])) )
{
        $login = $_POST["login"];
        $password = $_POST["pass"];
        //$stayLoggedIn;
        /*if (isset($_POST["stayLoggedIn"]))
                $stayLoggedIn = $_POST["stayLoggedIn"];
        else
                $stayLoggedIn = 'off';*/

        $dbh = mysql_connect($host, $user, $pswd) or die("Cannot connect to MySQL.");
        mysql_select_db($database) or die("Cannot connect to database.");


        $query = "SELECT `password` FROM `user` WHERE `login`='$login';";
        //var_dump($query);
        $res = mysql_query($query);
        //var_dump($res);
        $row = mysql_fetch_array($res);

		mysql_close($dbh);

        if ( ($row[0] == $password) )
        {		
				$_SESSION['login']=$login;
                $successfulLogin = true;
                setcookie("last_login", $login, time() + $cookieTTL*24*60*60);
				header('location: /chat/chat.php');
        }
		else
		{
			setcookie("last_login","");
			unset($_SESSION['login']);
		}
}
?>


<html>
<head>
<title>ChitChat - Main page</title>
</head>
<body>


<h2><center>ChitChat - Chat with registration</center></h2>
<h3><center>Sign in please:</center></h3>
<form action="index.php" method="POST">
<table align ="center" cellspacing="2" border="1" cellpadding="5">
<tr>
        <td>
                Login:
        </td>
        <td>
                <input type="text" name="login" value="
<?php
if (isset($_COOKIE["last_login"]))
{echo $_COOKIE["last_login"];}
?>
">
        </td>
</tr>
<tr>
        <td>
                Password:
        </td>
        <td>
                <input type="password" name="pass">
        </td>
</tr>
<!--
<tr>
        <td colspan=2>
                Stay logged in &nbsp<input type="checkbox" name="stayLoggedIn">
        </td>
</tr> 
-->
<tr>
        <td colspan=2>
                <p align="center">
                <input type="reset" value="Reset"><input type="submit" value="Sign in">
                </p>
        </td>
</tr>
</table>
</form>


<?php

        if ( ( !$successfulLogin ) &&  (isset($_POST["login"])) && ( isset($_POST["pass"])) )
		{
                echo "<center>Wrong login or password</center>";
		}
?>


<h4>
<center>If you have not registered yet,<br/>
you are welcomed to <a href="regist.php">the registration page.</a><center>
</h4>
</body>
</html>
